﻿package com.kuanter.kuanterauto.baseui;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKGeocoderAddressComponent;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.kuanter.kuanterauto.alipay.PartnerConfig;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.constants.NativeData;
import com.kuanter.kuanterauto.dataservices.PushServices;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.entity.KuanterService;
import com.kuanter.kuanterauto.entity.SiteInfo;
import com.kuanter.kuanterauto.entity.UserInfo;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.entity.XuNiAccount;
import com.kuanter.kuanterauto.param.ActivityHolder;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;


public class ProApplication extends Application {
	public static boolean slidingmenu = false;
	public static String loc_city = "";
	
	public static String state = "0";//0未开放，1开放		
	
	private List<KuanterService> list_kuanterService;  //服务列表
	List<VehicleInfo> list_vehicleInfo; //车辆信息缓存
	
	private static ProApplication instance;
	public boolean m_bKeyRight = true;
	
	public static List<SiteInfo> sort_default = new ArrayList<SiteInfo>();  //默认排序缓存
	public static List<SiteInfo> sort_distance = new ArrayList<SiteInfo>();  //距离排序缓存
	public static List<SiteInfo> sort_star = new ArrayList<SiteInfo>();		//星级排序缓存
	public static List<SiteInfo> sort_price_lowtohigh = new ArrayList<SiteInfo>();	//价格排序缓存
	public static List<SiteInfo> sort_price_hightolow = new ArrayList<SiteInfo>();
	
	public static String DEFAULT_SORT = "距离最近";		//默认排序标志，根据这个参数来显示列表
	public static String DISTANCE_SORT = "距离最近";
	public static String STAR_SORT = "评分最高";
	public static String PRICE_SORT_lowtohigh = "价格最低";
	public static String PRICE_SORT_hightolow = "价格从高到低";
	
	public static List<SiteInfo> cache_site = new ArrayList<SiteInfo>();
	
	public static int DEFAULT_SUM = 0;
	public static int DISTANCE_SUM = 0;
	public static int STAR_SUM = 0;
	public static int PRICE_LOW_HIGH_SUM = 0;
	public static int PRICE_HOGH_LOW_SUM = 0;
	
	public static String default_distance = "1KM";
	public static String default_condition = "全车标准清洗"; 

	public static final int KUANTER_HY = 0;//会员
	public static final int KUANTER_FW = 1;//服务
	public static final int KUANTER_GD = 2;//更多
	public static final int KUANTER_TQ = 3;//天气
	
	
	public static String downloadDir = "kuanterauto/";// 安装目录
	
	public static final String strKey = "6293A46969A861109E9F1FCD5A1ACBB059DB3C32"; //百度地图key
	public BMapManager mBMapManager = null;
	LocationClientOption option;
	
	//定位
	public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();
    public LocationData locData = null;
    MKSearch mSearch;

	DataLoader loader=null;
	
	Handler mHandler;  //当定位成功后发送通知
	public static int location_cuccess = 0;
	public static int location_fial = -200;
	private static boolean write_shareprefence = false;
	
	public static Stack<ActivityHolder> actStack = new Stack<ActivityHolder>(); // 存放act跳转
	
	int searchStatus = 0;    //1表示反地址解析，
	GeoPoint cityCenter;	//城市中心点
	public static int CENTER_OK = 90;	//解析成功后发送的msg.what
	
	//判断网络是否可用
		public boolean CheckNetworkState()
	    {
	        boolean flag = false;
	        ConnectivityManager manager = (ConnectivityManager)getSystemService(
	                Context.CONNECTIVITY_SERVICE);
	        if(manager.getActiveNetworkInfo() != null)
	        {
	            flag = manager.getActiveNetworkInfo().isAvailable();
	        }
	        if(!flag)
	        {
	            AlertDialog.Builder builder = new AlertDialog.Builder(this);
	            builder.setIcon(android.R.drawable.ic_dialog_alert);
	            builder.setTitle("网络状况");
	            builder.setMessage("当前网络不可用，是否设置网络");
	            builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
	                
	                @Override
	                public void onClick(DialogInterface dialog, int which) {
	                    // TODO Auto-generated method stub
	                    Intent mIntent = new Intent("/");
	                    ComponentName comp = new ComponentName("com.android.settings",
	                            "com.android.settings.WirelessSettings");
	                    mIntent.setComponent(comp);
	                    mIntent.setAction("android.intent.action.VIEW");
	                    startActivity(mIntent);
	                }
	            });
	            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	                
	                @Override
	                public void onClick(DialogInterface dialog, int which) {
	                    dialog.cancel();
	                }
	            });
	            builder.create();
	            builder.show();
	        }
	        
	        return flag;
	        
	    }
		
		
		public String deviceToken;
		public SharedPreferences sharedPreferences ;
		private Intent service;
		private HashMap<String, SoftReference<Bitmap>> sBitmaps;
		
		
		public void clearCache() {
			if(list_vehicleInfo != null) {
				list_vehicleInfo.clear();
				list_vehicleInfo = null;  //清除车辆信息缓存
			}
//			if(list_kuanterService != null) {
//				list_kuanterService.clear();  //清除服务列表缓存
//				list_kuanterService = null;
//			}
			if(null != sort_default){
//				sort_default.clear();  //默认排序的数据
			}
			if(null != sort_distance){
				sort_distance.clear();  //距离排序
			}
			if(null != sort_star){
				sort_star.clear();
			}
			if(null != sort_price_lowtohigh){
				sort_price_lowtohigh.clear();
			}
			if(null != sort_price_hightolow){
				sort_price_hightolow.clear();
			}
			/*if(null != cardInfoList){
				cardInfoList.clear();
			}*/
			ObjectCache.clear();
		}

		public String getDeviceToken(){
		 	TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
			String tmDevice, tmSerial, androidId;
			tmDevice = "" + tm.getDeviceId();
			tmSerial = "" + tm.getSimSerialNumber();
			androidId = ""+ android.provider.Settings.Secure.getString(this.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
			UUID deviceUuid = new UUID(androidId.hashCode(),((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
			return deviceUuid.toString();
	}
	
		@Override
		public void onCreate() {
			state = SharePrefenceUtil.getState(this);
			//调用jni赋值
			PartnerConfig.PARTNER = NativeData.getPartner();
			PartnerConfig.SELLER = NativeData.getSeller();
			PartnerConfig.RSA_PRIVATE = NativeData.getRSA_PRIVATE();
			PartnerConfig.RSA_ALIPAY_PUBLIC = NativeData.getRSA_ALIPAY_PUBLIC();
			MainConstants.HOST = NativeData.getHost();
			MainConstants.HOST_img = NativeData.getHOST_img();
//			MainConstants.HOST_test = NativeData.getHostTest();
			MainConstants.HOST_img_test = NativeData.getHOST_imgtest();
			
			//捕获异常处理
//			CrashHandler crashHandler = CrashHandler.getInstance();    
//            crashHandler.init(getApplicationContext());   
			
			//---------------TODO
			/*locData = new LocationData();
			locData.latitude = 30.600234;
			locData.longitude = 114.305277;
			loc_city = "武汉";*/
			//---------------------TODO
			
			initEngineManager(this);
			mLocationClient = new LocationClient(getApplicationContext());
			mLocationClient.registerLocationListener(myListener);
			option = new LocationClientOption();
			option.setOpenGps(true);
			option.setCoorType("bd09ll");
			option.setAddrType("all");
			option.setScanSpan(0);  //大于0表示这个时间间隔请求一次定位
			option.disableCache(true);  //启用缓存
			option.setPriority(LocationClientOption.GpsFirst);
			mLocationClient.setLocOption(option);
//			mLocationClient.start();
			//push
			this.deviceToken = this.getDeviceToken();
			boolean push = SharePrefenceUtil.getMessagePush(this);
			if (push) {
				service = new Intent(this,PushServices.class);
				startService(service);
			}
			
			mSearch = new MKSearch();
			mSearch.init(mBMapManager, new MKSearchListener() {
				
				@Override
				public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetPoiDetailSearchResult(int arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onGetAddrResult(MKAddrInfo res, int error) {
					// TODO Auto-generated method stub
					if (error != 0) {
						String str = String.format("错误号：%d", error);
						Toast.makeText(ProApplication.this, "地图查找失败",
								Toast.LENGTH_LONG).show();
						return;
					}
					MKGeocoderAddressComponent mac = res.addressComponents;
					if (mac != null && searchStatus  == 0) { //
						loc_city = mac.city;
						loc_city = loc_city.replace("市", "");
						Log.i("aaa", loc_city);
						if(write_shareprefence) {
							SharePrefenceUtil.setCity(getInstance(), loc_city);
							write_shareprefence = false;
						}
						if(mHandler != null) {
							Message message = mHandler.obtainMessage();
							message.obj = loc_city;
							if(!loc_city.equals("")) {
								message.what = location_cuccess;
							} else {
								message.what = location_fial;
							}
		                	mHandler.sendMessage(message);
		                }
						
						stopLocating();
					}
					
					if (searchStatus == 1) {
						setCityCenter(res.geoPt);
						mHandler.sendEmptyMessage(CENTER_OK);
					}
					
				}
			});
			super.onCreate();
		}
		
		public void stopLocating() {
			if(mLocationClient != null && mLocationClient.isStarted()) {
				mLocationClient.stop();
			}
		}
		
		public GeoPoint getCityCenter() {
			return cityCenter;
		}

		public void setCityCenter(GeoPoint cityCenter) {
			this.cityCenter = cityCenter;
		}

		public void getCenter(String cityName,Handler mHandler) {
			if(mSearch != null) {
				this.mHandler = mHandler;
				searchStatus = 1;
				mSearch.geocode(cityName, null);
			}
		}
		
		@Override
		//建议在您app的退出之前调用mapadpi的destroy()函数，避免重复初始化带来的时间消耗
		public void onTerminate() {
			// TODO Auto-generated method stub
		    if (mBMapManager != null) {
	            mBMapManager.destroy();
	            mBMapManager = null;
	        }
			super.onTerminate();
		}
		
		public void initEngineManager(Context context) {
	        if (mBMapManager == null) {
	            mBMapManager = new BMapManager(context);
	        }
	        

	        if (!mBMapManager.init(strKey,new MyGeneralListener())) {
	            Toast.makeText(ProApplication.getInstance().getApplicationContext(), 
	                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
	        }
		}
		
		public void startRequest(Handler mHandler) {
			this.mHandler = mHandler;
			if(mLocationClient.isStarted()) {
				mLocationClient.requestLocation();
			} else {
				mLocationClient.start();
			}
		}
		
		public void startRequest(Handler mHandler,boolean write) {
			write_shareprefence = write;
			this.mHandler = mHandler;
			if(mLocationClient.isStarted()) {
				mLocationClient.requestLocation();
			} else {
				mLocationClient.start();
			}
		}
		
		// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	    public static class MyGeneralListener implements MKGeneralListener {
	        
	        @Override
	        public void onGetNetworkState(int iError) {
	            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
	                Toast.makeText(ProApplication.getInstance().getApplicationContext(), "您的网络出错啦",
	                    Toast.LENGTH_LONG).show();
	            }
	            else if (iError == MKEvent.ERROR_NETWORK_DATA) {
	                Toast.makeText(ProApplication.getInstance().getApplicationContext(), "输入正确的检索条件",
	                        Toast.LENGTH_LONG).show();
	            }
	            // ...
	        }

	        @Override
	        public void onGetPermissionState(int iError) {
	            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
	                //��ȨKey����
	                Toast.makeText(ProApplication.getInstance().getApplicationContext(), 
	                        "权限不足", Toast.LENGTH_LONG).show();
	                ProApplication.getInstance().m_bKeyRight = false;
	            }
	        }
	    }
	    
	    
	// 定位监听
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData = new LocationData();
			locData.latitude = location.getLatitude();  //TODO
			locData.longitude = location.getLongitude();	//TODO
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			
			GeoPoint gp = new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
			if (location.getLocType() == BDLocation.TypeNetWorkLocation){
                String province = location.getProvince();
                String city = location.getCity();
                String district = location.getDistrict();
                String address = location.getAddrStr();
                
                loc_city = city;
                loc_city = loc_city.replace("市", "");
                
                Log.i("aaa", province + "--" + city + "--" + district + "--" + address);
                if(write_shareprefence) {
                	SharePrefenceUtil.setCity(getInstance(), city);
                	write_shareprefence = false;
                }
                if(mHandler != null) {
                	Message message = mHandler.obtainMessage();
                	message.what = location_cuccess;
                	message.obj = loc_city;
                	mHandler.sendMessage(message);
                }
            } else {
            	mSearch.reverseGeocode(gp);
            }
			
			mLocationClient.stop();

		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}
	
	public ProApplication() {
		instance = this;
		 
	}

	public static ProApplication getInstance() {
		return instance;
	}
	
	public List<KuanterService> getList_kuanterService() {
		return list_kuanterService;
	}

	public void setList_kuanterService(List<KuanterService> list_kuanterService) {
		this.list_kuanterService = list_kuanterService;
	}
	
	// TODO 车辆信息缓存
	public List<VehicleInfo> getList_vehicleInfo() {
		return list_vehicleInfo;
	}

	public void setList_vehicleInfo(List<VehicleInfo> list_vehicleInfo) {
		this.list_vehicleInfo = list_vehicleInfo;
	}
	private List<CardInfo> cardInfoList;

	public List<CardInfo> getCardInfoList() {
		return cardInfoList;
	}

	public void setCardInfoList(List<CardInfo> cardInfoList) {
		this.cardInfoList = cardInfoList;
	}
	private static String saveMoney ="";

	public String getSaveMoney() {
		return saveMoney;
	}

	public void setSaveMoney(String saveMoney) {
		this.saveMoney = saveMoney;
	}
	private ArrayList<Activity> activityList  = new ArrayList<Activity>();

	public ArrayList<Activity> getActivityList() {
		return activityList;
	}

	public void setActivityList(ArrayList<Activity> activityList) {
		this.activityList = activityList;
	}
	private UserInfo userInfo ;

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}
	
	private static boolean isGradeSuccessed = false;

	public static boolean isGradeSuccessed() {
		return isGradeSuccessed;
	}

	public static void setGradeSuccessed(boolean isGradeSuccessed) {
		ProApplication.isGradeSuccessed = isGradeSuccessed;
	}
	private XuNiAccount xuNiAccount ;

	public XuNiAccount getXuNiAccount() {
		return xuNiAccount;
	}

	public void setXuNiAccount(XuNiAccount xuNiAccount) {
		this.xuNiAccount = xuNiAccount;
	}
	
}
